<?php
class Sql {
    public static function queryWithConditions($conn, $tableName, $conditions = []) {
        // 检查输入参数
        if (!is_array($conditions)) {
            throw new Exception("条件参数必须是数组");
        }

        // 如果没有条件，则返回表中所有数据
        if (empty($conditions)) {
            $sql = "SELECT * FROM `$tableName`";
            $stmt = $conn->prepare($sql);
            if (!$stmt) {
                throw new Exception("SQL 准备失败: " . $conn->error);
            }
        } else {
            // 构建 WHERE 条件字符串
            $whereConditions = [];
            foreach ($conditions as $field => $value) {
                $whereConditions[] = "`$field` = ?";
            }
            $whereString = implode(" AND ", $whereConditions);

            // 构建 SQL 查询语句
            $sql = "SELECT * FROM `$tableName` WHERE " . $whereString;

            // 准备预处理语句
            if (!$stmt = $conn->prepare($sql)) {
                throw new Exception("SQL 准备失败: " . $conn->error);
            }

            // 获取参数类型字符串和参数数组
            $types = '';
            $params = [];
            foreach ($conditions as $field => $value) {
                if (is_int($value)) {
                    $types .= 'i';
                } elseif (is_float($value)) {
                    $types .= 'd';
                } elseif (is_string($value)) {
                    $types .= 's';
                } else {
                    throw new Exception("不支持的参数类型: " . gettype($value));
                }
                $params[] = $value;
            }

            // 绑定参数
            $stmt->bind_param($types, ...$params);
        }

        // 执行查询
        if (!$stmt->execute()) {
            throw new Exception("查询执行失败: " . $stmt->error);
        }

        // 获取结果
        $result = $stmt->get_result();
        $rows = [];
        while ($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }

        // 关闭语句
        $stmt->close();

        return $rows;
    }
}

$Data = new Sql();